package com.gosophia.conferenceManagement.common.ws.impl;

import java.util.ArrayList;
import java.util.List;

import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.gosophia.commons.DozerChangeUtil;
import com.gosophia.commons.exception.BusinessException;
import com.gosophia.conferenceManagement.common.dto.ConferenceJobHandleDTO;
import com.gosophia.conferenceManagement.common.dto.DocumentDTO;
import com.gosophia.conferenceManagement.common.entity.ConferenceJobData;
import com.gosophia.conferenceManagement.common.entity.Document;
import com.gosophia.conferenceManagement.common.service.ConferenceQueryService;
import com.gosophia.conferenceManagement.common.ws.ConferenceQueryWebService;
import com.gosophia.conferenceManagement.starting.dto.ConferenceAppDetailDTO;
import com.gosophia.conferenceManagement.starting.dto.ConferenceApplicationDTO;
import com.gosophia.conferenceManagement.starting.dto.ConferenceStartingDTO;
import com.gosophia.conferenceManagement.starting.entity.ConferenceApplicationJobData;
import com.gosophia.conferenceManagement.starting.entity.ConferenceStartingJobData;
import com.gosophia.conferenceManagement.starting.service.ConferenceStartingService;
import com.gosophia.taskManagement.dto.JobDTO;
import com.gosophia.taskManagement.entity.Job;
import com.gosophia.taskManagement.entity.JobData;
import com.gosophia.taskManagement.entity.Mission;
import com.gosophia.taskManagement.service.TaskManagementService;
import com.gosophia.userManagement.dto.UserInfoDTO;

/**
 * 会议查询接口ConferenceQueryWebService的实现
 * 
 * @author tianchunyu
 * 
 */
@Transactional
@Service("conferenceQueryWebService")
public class ConferenceQueryWebServiceImpl implements ConferenceQueryWebService {
	private static final String JOBTYPE_APPROVAL = "申请审批";
	private static final String APPLICATION_FINAL = "申请定稿";
	private static final String APPLICATION_MODIFY = "申请修改";

	@Autowired
	private ConferenceStartingService conferenceStartingService;
	@Autowired
	private ConferenceQueryService conferenceQueryService;
	@Autowired
	private TaskManagementService taskManagementService;
	@Autowired
	private Mapper dozer;

	@Override
	public DocumentDTO findDocumentByDocumentId(Long docId) {
		Assert.notNull(docId, "docId不能为null");
		Document document = conferenceQueryService
				.findDocumentByDocumentId(docId);

		DocumentDTO docDTO = new DocumentDTO();
		if (document != null) {
			docDTO = DozerChangeUtil.changeBeforeToAfter(document,
					DocumentDTO.class);
		}
		return docDTO;
	}

	public ConferenceStartingDTO findConferenceInfoByMissionId(Long missionId) throws BusinessException{
	    Mission mission =  taskManagementService.findMissionDetailByMissionId(missionId);
        if (mission.getFirstJob() == null) {
            return null;
        }
        // ConferenceStartingJobData任务信息
        ConferenceStartingJobData conferenceStartingJobData = (ConferenceStartingJobData) taskManagementService
                .findJobDataDetail(mission.getFirstJob().getJobId(),
                        ConferenceStartingJobData.class);
        // ConferenceApplicationJobData申请信息
        ConferenceApplicationJobData conferenceApplicationJobData = conferenceStartingService
                .getNewApplicationJobData(mission.getMissionId());
        ConferenceStartingDTO conferenceStartingDTO = new ConferenceStartingDTO();
        conferenceStartingDTO.setMissionId(mission.getMissionId());
        conferenceStartingDTO.setConferenceName(conferenceStartingJobData
                .getConferenceName());
        conferenceStartingDTO.setMissionCode(mission.getMissionCode());
        if (conferenceStartingJobData.getImportantLevel() != null) {
            conferenceStartingDTO.setImportentLevel(conferenceStartingJobData
                    .getImportantLevel().getDataValueId());
        }
        conferenceStartingDTO
                .setConferenceDescription(conferenceStartingJobData
                        .getConferenceDescription());
        conferenceStartingDTO.setPlanEndTime(conferenceStartingJobData
                .getPlanEndTime());
        conferenceStartingDTO.setConferenceType(conferenceStartingJobData
                .getConferenceType());
        //新增会议发起方式
        conferenceStartingDTO.setConferenceModel(conferenceStartingJobData.getConferenceModel());
        
        if (conferenceApplicationJobData != null) {
            conferenceStartingDTO.setPlanStartTime(conferenceApplicationJobData
                    .getPlanStartTime());
            conferenceStartingDTO.setMajorIssue(conferenceApplicationJobData
                    .getMajorIssue());
            conferenceStartingDTO
                    .setMajorParticipators(conferenceApplicationJobData
                            .getMajorParticipators());
            conferenceStartingDTO
                    .setApplicationInfo(conferenceApplicationJobData
                            .getApplicationInfo());
            if (conferenceApplicationJobData.getConfernceUnderTaker() != null) {
                conferenceStartingDTO
                        .setConfernceUnderTakerId(conferenceApplicationJobData
                                .getConfernceUnderTaker().getUserInfoId());
                conferenceStartingDTO
                        .setConfernceUnderTakerName(conferenceApplicationJobData
                                .getConfernceUnderTaker().getUserName());
            }
            if (conferenceApplicationJobData.getNextApproval() != null) {
                conferenceStartingDTO
                        .setNextHandlerId(conferenceApplicationJobData
                                .getNextApproval().getUserInfoId());
            }
            
        }
        return conferenceStartingDTO;
	}
	
	/**
	 * 查找会议的大任务及会议的申请信息
	 */
	@Override
	public ConferenceStartingDTO findConferenceMasterByJobId(Long jobId)
			throws BusinessException {
		Assert.isTrue(jobId != null, "jobId不能为null");
		Job job = taskManagementService.findJobDetailByJobId(jobId);
	 return	findConferenceInfoByMissionId(job.getMission().getMissionId());
 
	}

	@Override
	public ConferenceJobHandleDTO findConferenceJobHandleDTOByJobId(Long jobId)
			throws BusinessException {
		Assert.isTrue(jobId != null, "jobId不能为null");
		ConferenceJobHandleDTO conferenceJobHandleDTO = new ConferenceJobHandleDTO();
		ConferenceJobData conferenceJobData = (ConferenceJobData) taskManagementService
				.findJobDataDetail(jobId, ConferenceJobData.class);
		if (conferenceJobData == null) {
			return null;
		}
		conferenceJobHandleDTO.setConferenceJobHandId(conferenceJobData
				.getJobDataId());
		conferenceJobHandleDTO.setHandleAction(conferenceJobData
				.getTurningAction());
		conferenceJobHandleDTO.setJobId(conferenceJobData.getJob().getJobId());
		conferenceJobHandleDTO.setNextOperatorId(conferenceJobData
				.getNextApprovalId());
		conferenceJobHandleDTO.setOperatorId(conferenceJobData.getJob()
				.getOperator().getUserInfoId());
		conferenceJobHandleDTO.setOperatorName(conferenceJobData.getJob()
				.getOperator().getUserName());
		conferenceJobHandleDTO.setOperatorTime(conferenceJobData.getJob()
				.getActualEndTime());
		conferenceJobHandleDTO.setOpinion(conferenceJobData.getOpinion());

		return conferenceJobHandleDTO;
	}

	@Override
	public List<JobDTO> findHandleHistory(Long jobId) throws BusinessException {
		Assert.isTrue(jobId != null, "jobId不能为null");
		Job j = taskManagementService.findJobDetailByJobId(jobId);

		List<Job> jobs = taskManagementService
				.findJobByMissionTypeAndJobTypeFinished(j.getMission()
						.getMissionId(), JOBTYPE_APPROVAL);
		List<JobDTO> jobDTOs = new ArrayList<JobDTO>();
		for (Job job : jobs) {
			JobDTO jobDto = dozer.map(job, JobDTO.class);
			UserInfoDTO uDto = dozer.map(job.getOperator(), UserInfoDTO.class);
			jobDto.setOperatorDTO(uDto);
			jobDTOs.add(jobDto);
		}
		return jobDTOs;
	}

	/**
	 * 根据本次jobId查找上一个JobDTO
	 */
	@Override
	public JobDTO findPreDtoByJobId(Long jobId) throws BusinessException {
		Job job = taskManagementService.findJobDetailByJobId(jobId);
		Job preJob = job.getPreviousJob();
		if (preJob == null) {
			return null;
		}
		JobDTO jobDto = dozer.map(preJob, JobDTO.class);
		// 此处需要的字段自己配，暂时只需要jobId ^-^
		return jobDto;
	}

	/**
	 * 
	 */
	public List<ConferenceJobHandleDTO> findHandleRecords(Long missionId,
			String jobType) {
		List<ConferenceJobData> jobDatas = conferenceQueryService
				.findConferenceJobDataList(missionId, jobType);
		List<ConferenceJobHandleDTO> handleRecords = new ArrayList<ConferenceJobHandleDTO>();
		for (ConferenceJobData conferenceJobData : jobDatas) {
			ConferenceJobHandleDTO dto = new ConferenceJobHandleDTO();
			dto.setOperatorId(conferenceJobData.getJob().getOperator()
					.getUserInfoId());
			dto.setOperatorName(conferenceJobData.getJob().getOperator()
					.getUserName());
			dto.setOperatorTime(conferenceJobData.getJob().getActualEndTime());
			dto.setHandleAction(conferenceJobData.getTurningAction());
			dto.setOpinion(conferenceJobData.getOpinion());
			handleRecords.add(dto);
		}
		return handleRecords;

	}

	/*
	 * 根据jobId 查找对应的申请详细信息
	 * 
	 * @see
	 * com.gosophia.conferenceManagement.common.ws.ConferenceQueryWebService
	 * #loadConfAppDetail(java.lang.Long)
	 */
	@Override
	public ConferenceAppDetailDTO loadConfAppDetail(Long jobId)
			throws BusinessException {
		// 查找job -> ConferenceJobData
		// 如果是 ConferenceApplicationJobData 转化 申请信息
		// 读取处理信息
		ConferenceAppDetailDTO appDetail = new ConferenceAppDetailDTO();
		JobData data = taskManagementService.findJobDataDetail(jobId,
				ConferenceJobData.class);
		if (data == null)
			return null;

		ConferenceJobData confJobData = (ConferenceJobData) data;

		appDetail.setConfJobHandleDTO(loadConfJobHandleInfo(confJobData));
		appDetail.setConfAppDTO(loadconfApplInfo(confJobData));
		appDetail.setJobType(confJobData.getJob().getJobType());
		return appDetail;
	}

	/**
	 * 提取会议申请信息
	 * 
	 * @param confJobData
	 * @return 会议申请信息
	 */
	private ConferenceApplicationDTO loadconfApplInfo(
			ConferenceJobData confJobData) {
		if (!(confJobData instanceof ConferenceApplicationJobData)) {
			return null;
		}
		ConferenceApplicationDTO confAppDTO = new ConferenceApplicationDTO();
		ConferenceApplicationJobData confAppJobData = (ConferenceApplicationJobData) confJobData;
		confAppDTO.setPlanStartTime(confAppJobData.getPlanStartTime());// 计划开始时间
		confAppDTO.setMajorIssue(confAppJobData.getMajorIssue());// 主要议题
		confAppDTO
				.setMajorParticipators(confAppJobData.getMajorParticipators());// 主要参会人员
		confAppDTO.setConfernceUnderTakerId(confAppJobData
				.getConfernceUnderTaker().getUserInfoId());// 指定会议承办人id
		confAppDTO.setConfernceUnderTakerName(confAppJobData
				.getConfernceUnderTaker().getUserName());// 指定会议承办人名称
		confAppDTO.setApplicationInfo(confAppJobData.getApplicationInfo());// 会议申请理由
		return confAppDTO;
	}

	/**
	 * 提取job处理信息
	 * 
	 * @param confJobData
	 * @return 任务处理信息
	 */
	private ConferenceJobHandleDTO loadConfJobHandleInfo(
			ConferenceJobData confJobData) {
		Assert.notNull(confJobData, "提取job处理信息时，conferenceJobData 不能为空");
		ConferenceJobHandleDTO handleDTO = new ConferenceJobHandleDTO();
		handleDTO.setHandleAction(confJobData.getTurningAction());// 处理动作
		handleDTO.setOpinion(confJobData.getOpinion());// 处理意见
		handleDTO.setOperatorName(confJobData.getJob().getOperator()
				.getUserName());// 操作人名称
		handleDTO.setOperatorTime(confJobData.getJob().getActualEndTime());// 操作时间
		// handleDTO.setNextOperatorId(confJobData.getNextApproval().getUserInfoId());//下一个处理人
		return handleDTO;
	}

}